//
//  Untils.m
//  GasCome
//
//  Created by zfc on 2020/4/25.
//  Copyright © 2020 zfc. All rights reserved.
//

#import "Untils.h"

@implementation Untils

+ (BOOL) cheackPhoneNumValid:(NSString *)phone {
    NSString *regex = @"^[1][3456789][0-9]{9}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:phone];
    return isValid;;
}

+ (BOOL)cheackPasswordValid:(NSString *)pwd {
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]{6,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:pwd];
    return isMatch;
}

+(NSString *) phoneNumberHiddenCenter:(NSString *)phone {
    if (![Untils cheackPhoneNumValid:phone]) {
        return nil;
    }
    NSString *startStr = [phone substringWithRange:NSMakeRange(0, 3)];
    NSString *endStr = [phone substringWithRange:NSMakeRange(phone.length-4, 4)];
    NSString *hiddenStr = [NSString stringWithFormat:@"%@****%@",startStr,endStr];
    return hiddenStr;
}

+ (BOOL)isChinese:(NSString *)str {
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSString *)setTimeWithTime:(NSString *)time {
    NSTimeInterval time1 = [time doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time1];
    return [date stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSString *)setTimeWithTime:(NSString *)time format:(NSString *)format{
    NSTimeInterval time1 = [time doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time1];
    return [date stringWithFormat:format];
}

+ (BOOL) validateTelphone:(NSString *)telphone {
    NSString *phoneRegex = @"^1+[3578]+\\d{9}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:telphone];
}

+ (NSString *)convertToJsonData:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

+ (NSString *)arrayToJSONString:(NSArray *)array{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

+ (NSDate *)changeStrToDateWithStr:(NSString *)dateStr format:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSDate *date = [dateFormatter dateFromString:dateStr];
    return date;
}

+ (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font: (CGFloat)font {
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
return rect.size.height;
}


+ (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font{
CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
context:nil];
return rect.size.width;
}


+ (NSDate *)getLocalDateFormatAnyDate:(NSDate *)anyDate {
    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    NSTimeZone *desTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [desTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}

+(id)parseJSONStringToNSDictionary:(NSString *)JSONString {

NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

NSError *error = nil;

id jsonObject = [NSJSONSerialization

JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments

error:&error];

if (jsonObject != nil && error == nil){

NSLog(@"反序列化成功...");

if ([jsonObject isKindOfClass:[NSDictionary class]]){

NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;

NSLog(@"反序列化后的dictionary数据 = %@", deserializedDictionary);

return deserializedDictionary;

}

else if ([jsonObject isKindOfClass:[NSArray class]]){

NSArray *deserializedArray = (NSArray *)jsonObject;

NSLog(@"反序列化json后的数组 = %@", deserializedArray);

return deserializedArray;

}else {

return nil;

}

}else{

NSLog(@"%@", error);

NSLog(@"反序列化时发生一个错误");

return nil;

}

}

@end
